<?php
namespace Pw\MainBundle\EventListener;

use Doctrine\ORM\Event\PreUpdateEventArgs;
use Pw\MainBundle\Entity\Talent;
use Pw\MainBundle\Entity\Chapter;
use Pw\MainBundle\Classes\NFAParse;

class TalentParse
{
	protected $container;

	public function __construct($container)
	{
		$this->container = $container;
	}
    public function prePersist($args)
    {
        $entity = $args->getEntity();
        $em = $args->getEntityManager();

        if ($entity instanceof Talent)
        {
			$parser = new NFAParse($em, $this->container->get('request'), $this->container->get('router'));
			$entity->setParsedDescription($parser->parse($entity->getDescription()));
        }
        if ($entity instanceof Chapter)
        {
			$parser = new NFAParse($em, $this->container->get('request'), $this->container->get('router'));
			$entity->setParsedText($parser->parse($entity->getRawText()));
        }
    }
	public function preUpdate(PreUpdateEventArgs $args)
	{
        $entity = $args->getEntity();
        if (($entity instanceof Talent) && $args->hasChangedField('description')) { 
			$em = $args->getEntityManager();
			$uow = $em->getUnitOfWork();
			$parser = new NFAParse($em, $this->container->get('request'), $this->container->get('router'));
			$entity->setParsedDescription($parser->parse($entity->getDescription()));
			$uow->recomputeSingleEntityChangeSet($em->getClassMetadata("PwMainBundle:Talent"), $entity);
		}
        elseif (($entity instanceof Chapter) && $args->hasChangedField('rawText')) { 
			$em = $args->getEntityManager();
			$uow = $em->getUnitOfWork();
			$parser = new NFAParse($em, $this->container->get('request'), $this->container->get('router'));
			$entity->setParsedText($parser->parse($entity->getRawText()));
			$uow->recomputeSingleEntityChangeSet($em->getClassMetadata("PwMainBundle:Chapter"), $entity);
		}
	}
}
